package org.xfy.sys.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.xfy.base.util.AjaxResult;
import org.xfy.org.domain.Logininfo;
import org.xfy.org.domain.dto.LoginDto;
import org.xfy.org.service.ILogininfoService;
import org.xfy.sys.domain.User;
import org.xfy.sys.domain.Wxuser;
import org.xfy.sys.mapper.UserMapper;
import org.xfy.sys.mapper.WxuserMapper;

@RestController
public class TripartiteLoginController {
    @Value("${wechat.appid}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ILogininfoService logininfoService;
    private static final String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    private static final String wechatinfo = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s";

    @GetMapping("/wechat/login/{code}")

    public AjaxResult wechatLogin(@PathVariable("code") String code) {
        //获取token
        String format = String.format(tokenUrl, appid, secret, code);
        String json = HttpUtil.get(format);
        //获取userinfo
        JSONObject jsonObject = JSONObject.parseObject(json);
        Object access_token = jsonObject.get("access_token");
        Object openid = jsonObject.get("openid");
        String userinfo = String.format(wechatinfo, access_token.toString(), openid.toString());
        String s = HttpUtil.get(userinfo);
        Wxuser wxuser = JSONObject.parseObject(s, Wxuser.class);
        //1.第一次登陆，跳转绑定页面
        Wxuser one = wxuserMapper.finOneByopenid(wxuser.getOpenid());
        if (one == null) {
            wxuserMapper.add(wxuser);
            return AjaxResult.me().setResultObj(wxuser.getOpenid()).setMessage("noBind").setSuccess(false);
        }
        //2.第二次登陆，没有绑定账号
        if (one.getUserId() == null) {
            return AjaxResult.me().setResultObj(one.getOpenid()).setMessage("noBind").setSuccess(false);
        }
        //3.第二次登陆，已经绑定过账号,进行登陆
        User user = userMapper.findOne(one.getUserId());
        LoginDto loginDto = new LoginDto();
        loginDto.setType(1);
        loginDto.setUsername(user.getUsername());
        loginDto.setPassword(user.getPassword());
        return logininfoService.login(loginDto, false);
    }
}
